import { useMemo, useState } from "react";

interface UsePaginationProps  {
  // 总数
  total: number;
  // 每页条数
  pageSize: number;
  // 当前页
  currentPage?: number;
  // 加载数据方法
  loadData?: (page: number) => void;
}

interface UsePaginationReturn {
  // 当前页
  currentPage: number,
  // 总页数
  totalPage: number,
  // 总条数
  total: number,
  paginationRange: (number | string)[];
  // 下一页
  nextPage: () => void;
  // 上一页
  prevPage: () => void;
  // 跳转指定页数
  goToPage: (page: number) => void;
  // 设置每页大小
  setPageSize: (size: number) => void;
  // 设置总数
  setTotal: (size: number) => void;
}


/**
 * 分页Hook
 * @param param0 
 * @returns 
 */
const usePagination = ({ pageSize, total, currentPage, loadData }: UsePaginationProps): UsePaginationReturn => {
  // 总条数
  const [dataTotal, setDataTotal] = useState<number>(total || 0);
  // 页码
  const [_pageIndex, setPageIndex] = useState<number>(currentPage || 1);
  // 每页数
  const [_pageSize, setPageSize] = useState<number>(pageSize || 1);
  // 总页数
  const pageTotal = useMemo(() => {
    if (dataTotal > 0 && dataTotal < _pageSize) return 1;
    return Math.ceil(dataTotal / _pageSize);
  }, [_pageSize, dataTotal])

  /**
   * 页码切换
   * @param page 
   */
  const onPageChange = async (page: number) => {
    setPageIndex(page);
    if (typeof loadData === 'function') {
      loadData(page)
    }
  }
  const result =  {
    currentPage: _pageIndex,
    totalPage: pageTotal,
    total: dataTotal,
    paginationRange: [],
    nextPage: () => {
      onPageChange(_pageIndex+1)
    },
    prevPage: () => {
      onPageChange(_pageIndex-1)
    },
    goToPage: (page: number) => {
      if (page > pageTotal) {
        throw new Error('The number of pages to be jumped cannot exceed the total number of pages');
      }
      onPageChange(page)
    },
    setPageSize: (size: number) => {
      setPageSize(size)
    },
    setTotal: (total: number) => {
      setDataTotal(total);
    }
  }
  return result;
}

export default usePagination;